package com.Controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.dto.QueryDTO;
import com.entity.Employee;
import com.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("employee")
public class EmployeeController {
    private final static Logger log = LoggerFactory.getLogger(EmployeeController.class);


    @Autowired
    private EmployeeService employeeService;

    @Value("${photo.file.dir}")
    private String realpath;

    @Autowired
    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }


    @RequestMapping("export")
    public void exportExcel(HttpServletResponse response) throws IOException {

        List<Employee> employees = employeeService.lists();
        //生成excel
        //输出头像
        employees.forEach(employee -> {
            employee.setPhoto(realpath+"/"+employee.getPhoto());
        });
        log.info("导出当前数据库中的数据总数为：[{}]",employees.size());
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户列表信息","用户信息"),Employee.class,employees);
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("员工信息列表.xls","UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();

    }

    @RequestMapping("import")
    public String importExcel(MultipartFile excelFile) throws Exception {
       log.info("文件名:[{}]",excelFile.getOriginalFilename());

        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
     List<Employee> employees =  ExcelImportUtil.importExcel(excelFile.getInputStream(),Employee.class,params);
     employees.forEach(System.out::println);
        employeeService.saveAll(employees);
        return "redirect:/employee/findByPage";
 //卡在图片上传处
    }


    @RequestMapping("delete")
    public String delete(Integer id){
        log.debug("删除的员工id",id);
       String photo = employeeService.findById(id).getPhoto();
        employeeService.delete(id);

       File file = new File(realpath,photo);
       if (file.exists()) file.delete();
        return "redirect:/employee/findByPage";
    }

    //更新用户信息
    @RequestMapping("update")
    public String update(Employee employee, MultipartFile img) throws IOException {

        log.debug("更新之后员工信息: id:{},姓名:{},工资:{},所属部门：{}，生日:{},性别:{},手机号:{},邮箱:{}",
                employee.getId(), employee.getName(), employee.getSalary(),employee.getDeid(), employee.getBirthday(),employee.getGender(),employee.getTelephone(),employee.getEpemail());
        //1.判断是否更新头像
        boolean notEmpty = !img.isEmpty();
        log.debug("是否更新头像: {}", notEmpty);
        if (notEmpty) {//1.删除老的头像 根据id查询原始头像
            String oldPhoto = employeeService.findById(employee.getId()).getPhoto();
            File file = new File(realpath, oldPhoto);
            if (file.exists()) file.delete();//删除文件
            //2.处理新的头像上传
            String originalFilename = img.getOriginalFilename();
            String newFileName = uploadPhoto(img, originalFilename);
            //3.修改员工新的头像名称
            employee.setPhoto(newFileName);

        }
        //4.没有更新头像直接更新基本信息
        employeeService.update(employee);
        return "redirect:/employee/findByPage";//更新成功,跳转到员工列表
    }

    private String uploadPhoto(MultipartFile img, String originalFilename) throws IOException {
        String fileNamePrefix =new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = fileNamePrefix+fileNameSuffix;
        img.transferTo(new File(realpath,newFileName));
        return newFileName;
    }

    //根据id查用户信息
    @RequestMapping("detail")
    public String detail(Integer id,Model model){
        log.debug("查询当前用户:{}",id);
        //查id
        Employee employee =  employeeService.findById(id);
        System.out.println(employee);
        model.addAttribute("employee",employee);
        return "updateEmp";
    }

    /*保存员工信息*/

    @RequestMapping("save")
    public String save(Employee employee, MultipartFile img) throws IOException {
        log.debug("姓名:{},薪资：{}，所属部门:{},生日：{},性别:{},电话:{},邮箱:{}",
                employee.getName(),employee.getSalary(),employee.getDeid(),employee.getBirthday(),employee.getGender(),employee.getTelephone(),employee.getEpemail());
        String originalFilename = img.getOriginalFilename();
        log.debug("头像名称:{}",originalFilename);
        log.debug("头像大小：{}",img.getSize());
        log.debug("头像传输路径:{}",realpath);
        //处理头像的上传+修改文件名
        String newFileName = uploadPhoto(img,originalFilename);
//        保存员工信息
          employee.setPhoto(newFileName);//保存头像姓名
          employeeService.save(employee);
        return "redirect:/employee/findByPage";
    }


    //信息分页
    //todo 1.改为统一用一个对象接受  2.
    @RequestMapping("findByPage")
    public String findByPage(@RequestBody QueryDTO queryDTO, Model model){

       queryDTO.setPageNow(queryDTO.getPageNow()==null?1:queryDTO.getPageNow());
       queryDTO.setPageSize(queryDTO.getPageSize()==null?4:queryDTO.getPageSize());
        // int start=0;
        // if(queryDTO.getPageNow()==null){
        //     start=1;
        // }else {
        //     start = Integer.valueOf(queryDTO.getPageNow());
        //     if (start < 1) {
        //         start = 1;
        //     }
        // }
        List<Employee> employees = employeeService.findByPage(queryDTO);
        String totals = employeeService.findTotals();

        // model.addAttribute("start",start);
        // model.addAttribute("employees",employees);
        // model.addAttribute("total",totals);
        model.addAttribute("total",totals);
        return "emplist";
    }

    @RequestMapping("lists")
    public String lists(Model model,Employee employee){
           log.debug("查询所有员工信息");
          List<Employee> employeeList = employeeService.lists();
          /*System.out.println(employeeList.get(0));*/
          model.addAttribute("employeeList",employeeList);

           return "emplist";
    }



}
